package com.vicene.gmail.cart.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.vicene.gmail.cart.feign.ProductFeignService;
import com.vicene.gmail.cart.interceptor.CartInterceptor;
import com.vicene.gmail.cart.service.CartService;
import com.vicene.gmail.cart.vo.Cart;
import com.vicene.gmail.cart.vo.CartItem;
import com.vicene.gmail.cart.vo.SkuInfoVo;
import com.vicene.gmail.cart.vo.UserInfoTo;
import com.vicene.gmail.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private final static String CART_PREFIX = "gmail:cart:";

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;


    @Override
    public CartItem addToCart(Long skuId, Long num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String ,Object , Object>  cartOps = getCartOps();

        String res  = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(res)){
            CartItem cartItem = new CartItem();

            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(()->{
                R skuInfo = productFeignService.info(skuId);
                String s = JSON.toJSONString(skuInfo.get("skuInfo"));
                SkuInfoVo data = JSON.parseObject(s , new TypeReference<SkuInfoVo>(){});
                cartItem.setCheck(true);
                cartItem.setCount(Integer.valueOf(num.toString()));
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            },executor);

            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(()->{
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            },executor);

            CompletableFuture.allOf(getSkuInfoTask , getSkuSaleAttrValues).get();
            cartOps.put(skuId.toString() , JSON.toJSONString(cartItem) );
            return cartItem;

        }else{
            CartItem cartItem = JSON.parseObject(res , CartItem.class);
            cartItem.setCount((int) (cartItem.getCount() + num));
            cartOps.put(skuId.toString() , JSON.toJSONString(cartItem));
            return cartItem;
        }



    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String ,Object , Object>  cartOps = getCartOps();
        CartItem data = JSON.parseObject((String) cartOps.get(skuId.toString()), CartItem.class);
        return data;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() != null){
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if(tempCartItems != null){
                for(CartItem item: tempCartItems){
                    addToCart(item.getSkuId() ,Long.valueOf(item.getCount().toString()) );
                }
                clearCart(tempCartKey);
            }
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }else{
            String userKey = CART_PREFIX + userInfoTo.getUserKey();
            cart.setItems(getCartItems(userKey));
        }
        return cart;
    }

    private BoundHashOperations<String ,Object , Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        String cartKey = "";
        if(userInfoTo.getUserId() != null){
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else{
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String ,Object , Object> operations =  stringRedisTemplate.boundHashOps(cartKey);
        return operations;
    }


    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String ,Object , Object> hashOps =  stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values  =hashOps.values();
        if(!CollUtil.isEmpty(values)){
            List<CartItem> list = values.stream().map((obj) ->{
                String str = (String) obj;

                return JSON.parseObject(str , CartItem.class);
            }).collect(Collectors.toList());
            return list;
        }
        return new ArrayList<>();
    }

    @Override
    public void clearCart(String cartKey){
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String ,Object , Object>  cartOps = getCartOps();

        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        cartOps.put(skuId.toString() ,JSON.toJSONString(cartItem) );

    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String ,Object , Object>  cartOps = getCartOps();
        cartOps.put(skuId.toString() ,JSON.toJSONString(cartItem) );
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String ,Object , Object>  cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() ==null){
            return  null;
        }else{
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().
                    filter(item -> item.getCheck()).map(item -> {
                        R price = productFeignService.getPrice(item.getSkuId());
                        String data =  (String)price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    }).collect(Collectors.toList());
            return collect;
        }
    }

}
